package top.snoweagle.simple.console.security.auth.handler;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import top.snoweagle.simple.console.common.domain.http.RestResponse;
import top.snoweagle.simple.console.common.domain.http.UserSession;
import top.snoweagle.simple.console.common.enums.Restful;
import top.snoweagle.simple.console.security.annotation.Authorization;
import top.snoweagle.simple.console.security.auth.AuthorizingProxy;
import top.snoweagle.simple.console.security.auth.RestfulAuthorizingProxy;
import top.snoweagle.simple.console.security.auth.TokenManager;
import top.snoweagle.simple.console.security.enums.AuthEnum;
import top.snoweagle.simple.console.security.model.AuthorizationInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by snoweagle on 5/28/16.
 */
@Component("authorizationInterceptor")
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    protected final Logger LOG = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private TokenManager tokenManager;
    @Autowired
    AuthorizingProxy authorizingProxy;

    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Authorization annotation  = handlerMethod.getMethodAnnotation(Authorization.class);
        if(annotation!=null){
            //从header中得到token
            String token = request.getParameter(AuthEnum.Token.getCode());
            //验证token
            LOG.info("token:[{}]", token);
            if (tokenManager.check(token)) {
                //如果token验证成功，将token对应的用户id存在request中，便于之后注入
//            request.setAttribute(Constants.CURRENT_USER_ID, model.getUserId());
                if(request.getRequestURI().endsWith("index")){
                    RestResponse restResponse = getUserInfo(token);
                    request.setAttribute(Restful.RESPONSE.getCode(),restResponse);
                }
                return true;
            } else{  //如果验证token失败，并且方法注明了Authorization，返回401错误
//                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                LOG.warn("认证失败.token:{}",token);
                request.setAttribute("LOGIN_MESSAGE","登录超时");
                response.sendRedirect(request.getContextPath()+"/");
                return false;
            }
        }
        return true;
    }
    private RestResponse getUserInfo(String token){
        UserSession userSession = tokenManager.get(token);

        AuthorizationInfo authorizationInfo= authorizingProxy.doGetAuthorization(userSession.getUserId());
        return authorizingProxy.getIndexInfo(userSession,authorizationInfo);
    }

}